package com.chahu.servlet.front;

import com.alibaba.fastjson.JSON;
import com.chahu.common.Result;
import com.chahu.entity.Snack;
import com.chahu.service.FruitService;
import com.chahu.service.impl.FruitServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/fruit")
public class FruitServlet extends HttpServlet {

    FruitService fruitService;
    @Override
    public void init() throws ServletException {
        fruitService = new FruitServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf-8");
        List<Snack> fruitList = fruitService.getFruitList();
        try (PrintWriter writer = resp.getWriter()) {
            if(fruitList == null){
                writer.write(JSON.toJSONString(Result.error("操作失败")));
            }
            writer.write(JSON.toJSONString(Result.success(JSON.toJSONString(fruitList))));
        }
    }
}
